package com.fulihui.usercore.core.counter;

import com.fulihui.usercore.condition.UserCondition;
import com.fulihui.usercore.config.RedisUtil;
import com.fulihui.usercore.core.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import javax.annotation.PostConstruct;

/**
 * @author Willard.Hu on 2016/11/30 0030.
 */
@Component
public class AllUsersCounter implements Counter, Increase {

    /**
     * Redis key
     */
    static final String ALL_USERS_COUNT_REDIS_KEY = "FULIHUI_ALL_USER_COUNT";
    /**
     * 存活时间30天
     */
    static final int ALIVE_SECONDS = 60 * 60 * 24 * 30;

    @Autowired
    UserRepository userRepository;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 同步数据库
     */
    @PostConstruct
    public void sync() {

        redisUtil.set(ALL_USERS_COUNT_REDIS_KEY, String.valueOf(countAllFromDB()), ALIVE_SECONDS);

    }

    /**
     * 自增
     *
     * @return 增加后的值
     */
    @Override
    public long incr() {

        if (redisUtil.hasKey(ALL_USERS_COUNT_REDIS_KEY)) {
            long count = redisUtil.incr(ALL_USERS_COUNT_REDIS_KEY, 1);
            redisUtil.expire(ALL_USERS_COUNT_REDIS_KEY, ALIVE_SECONDS);
            return count;
        }
        sync();
        return count();

    }

    /**
     * 获得用户数量
     *
     * @return
     */
    @Override
    public long count() {

        if (redisUtil.hasKey(ALL_USERS_COUNT_REDIS_KEY)) {
            return Long.parseLong((String) redisUtil.get(ALL_USERS_COUNT_REDIS_KEY));
        }
        sync();
        return Long.parseLong((String) redisUtil.get(ALL_USERS_COUNT_REDIS_KEY));

    }

    /**
     * 查询数据库中的所有用户数
     *
     * @return 所有用户数
     */
    private long countAllFromDB() {
        return userRepository.totalCount(new UserCondition());
    }

}
